<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookHomeManageShop;
use App\Models\BookHomeReturnAddress;
use App\Models\Manage;
use App\Models\Shop;
use App\Validate\ShopValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 书店管理
 */
class ShopController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new Shop();
        $this->validate = new ShopValidate();
    }


    /**
     * 书店筛选列表
     * @param way 类型 1开通荐购方式，线上线下等服务，2 只开通线下、3 只开通线上  多个逗号分隔
     */
    public function filterList()
    {
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }
        $way = $this->request->way;
        $res = $this->model->lists(['id', 'name'], $way, null, $shop_all_id, 100);

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res['data']); //只返回数据
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(文章标题)
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $keywords = request()->keywords;

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }
        $res = $this->model->lists(null, null, $keywords, $shop_all_id, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['intro'] = strip_tags($val['intro']);
            $res['data'][$key]['deliver_address'] = $bookHomeReturnAddressModel->getDeliverAddress(1,$val['id']);//获取邮递发货地址
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, '获取成功', true, $res); //只返回数据
    }

    /**
     * 详情
     * @param id int 文章id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }
        $res = $this->model->detail($this->request->id, $shop_all_id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param name string 书店名称 必填
     * @param img string 封面 必填
     * @param province string 省 必填
     * @param city string 市 必填
     * @param district string 区县  
     * @param address string 详细地址
     * @param tel string 联系手机号码
     * @param contacts string 联系人
     * @param intro string 简介
     * @param way 服务类型 1开通荐购方式，线上线下等服务，2 只开通线下、3 只开通线上  多个逗号分隔
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_exists = $this->model->nameIsExists($this->request->name, 'name');
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        DB::beginTransaction();
        try {
            //获取经纬度
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                throw new  Exception($map);
            }
            $this->request->merge(['lon' => $map['lon'], 'lat' => $map['lat']]);
            $this->request->merge(['manage_id' => $this->request->manage_id]);
            $shop_id = $this->model->add($this->request->all());

            //自动修改此书店权限在此账号上
            $bookHomeManageShopModel = new BookHomeManageShop();
            $bookHomeManageShopModel->addManageShopAuth($this->request->manage_id , $shop_id);

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

     /**
     * 修改
     * @param id string 书店id 必填
     * @param name string 书店名称 必填
     * @param img string 封面 必填
     * @param province string 类型id 必填
     * @param city string 内容 必填
     * @param district string 是否置顶   只能置顶3条  1 是  2 否
     * @param address datetime 创建时间  用户手动选择的时间
     * @param tel datetime 创建时间  用户手动选择的时间
     * @param contacts datetime 创建时间  用户手动选择的时间
     * @param intro datetime 创建时间  用户手动选择的时间
     * @param way 服务类型 1开通荐购方式，线上线下等服务，2 只开通线下、3 只开通线上  多个逗号分隔
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || !in_array($this->request->id , $shop_all_id)) {
            return $this->returnApi(202, '您无权操作此书店数据'); //无权限访问
        }
        $is_exists = $this->model->nameIsExists($this->request->name, 'name', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        DB::beginTransaction();
        try {
            //获取经纬度
            $map = $this->getLonLatByAddress($this->request->province . $this->request->city . $this->request->district . $this->request->address);
            if (is_string($map)) {
                throw new  Exception($map);
            }
            $this->request->merge(['lon' => $map['lon'], 'lat' => $map['lat']]);

            $this->model->change($this->request->all());

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 删除
     * @param id int 新闻id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || !in_array($this->request->id , $shop_all_id)) {
            return $this->returnApi(202, '您无权操作此书店数据'); //无权限访问
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

}
